

import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { svgBuilder } from "./src/plugin/icons/svgBuilder";
// @ts-ignore
import ElementPlus from "unplugin-element-plus/vite";
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
// @ts-ignore
import path from 'path'
import postCssPxToRem from "postcss-pxtorem"
import {defineConfig, loadEnv} from "vite";
// const path = require("path");
import  { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'

const pathSrc = path.resolve(__dirname, 'src')
function _resolve(dir) {
  return path.resolve(__dirname, dir);
}
// https://vitejs.dev/config/
export default ({ mode }: any ) => {

  const env = loadEnv(mode, process.cwd());
  // console.log(mode);  development
  console.log(env);
  // console.log(process.env);  环境变量
  return defineConfig({
    resolve: {
      alias: {
        // 如果报错__dirname找不到，需要安装node,执行npm install @types/node --save-dev
        "@": path.resolve(__dirname, "src"),
        "views": '@/views',
        "assets": '@/assets',
        "common": '@/common',
        "components": '@/components',
        "store": '@/store',
        "router": '@/router',
      },
      // 省略文件后缀
      extensions: ['', '.js', '.json', '.vue', '.scss', '.css', '.ts']
    },
    plugins: [
      vue(),
      ElementPlus({}),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          // Auto import icon components
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          // Auto register icon components
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),],
      }),
      Icons({
        autoInstall: true,
      }),
      svgBuilder("./src/plugin/icons/svg/"),
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true
      }),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      })
    ],
    base: env.VITE_PUBLIC_PATH,
    server: {
      port: 9000,
      cors: true,
      host: "0.0.0.0",
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "${path.resolve(__dirname, 'src/assets/styles/variables.less')}";`,
          // additionalData2: `@import "${path.resolve(__dirname, 'src/assets/styles/mixins.less')}";`
        },
      },
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 16, // 1rem的大小
            propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
          })
        ]
      },
    },
    build: {
      outDir: "dist",
      // 9月更新
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: false, //是否构建source map 文件
      // 10月更新
      minify: "terser", // 混淆器，terser 构建后文件体积更小，'terser' | 'esbuild'
      chunkSizeWarningLimit: 1500, //chunk 大小警告的限制，默认500KB
      rollupOptions: {
        output: {
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
          chunkFileNames: 'static/js/[name]-[hash].js', // 用于命名代码拆分时创建的共享块的输出命名，[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        }
      },
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
        // 10月更新
        output: {
          comments: true, // 去掉注释内容
        },
      },
    },
  });
}
